<?php
namespace control;
/*
*部门类
*/
class contactStaffClass extends adIndexClass
{
    private const page  = 'contactStaff'; # 权限
    private const table = 'staff'; # 数据表
    private const title = '员工通讯录';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'job'          => [
                        'name'  => L('person.table.zhi_wei'),
                        'width' => 400,
                    ],
                    'name'  => [
                        'name'  => L('person.table.xing_ming'),
                        'width' => 400,
                    ],
                    'tel'         => [
                        'name'  => L('person.table.shou_ji_hao'),
                        'width' => 400,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*职位入口页*/
    public function home()
    {
        $option['click'] = 'replaceRight(this, \'contactStaff\')';
        $all = departmentClass::getDepartmentAll($option);
        //返回
        $rightHtml = $this->homeRight();
        $html =  componentClass::leftNav([
            'title'=>L('person.table.sou_suo_bu_men'),
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        //返回
        return $this->homeFun($html);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('person.table.zwmc') => text(array("name" => "jobName")),
                    L('person.table.xing_ming') => text(array("name" => "name")),
                    L('person.table.dian_hua') => text(array("name" => "tel")).
                        hidden(['name'=>'objId', 'value'=>$this->post('objId')]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function homeRight()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->search($html, layout: 'pop', toolButton: $button);
    }

    /**
     * 异步加载
     *
     */
    public function homeRightJson()
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }
    public function homeRightJsonSearch()
    {
        return $this->homeSearch();
    }

    /*职位列表*/
    public function homeSearch()
    {
        //like查询数组
        $like = [
            "name"    => $this->post('name'),
            "tel"     => $this->post('tel'),
        ];
        //全等查询数组
        $equal = [

        ];
        $mWhere = search([
            'like'=> [
                'name' => $this->post('jobName')
            ],
            '='=>[
                'departmentId' => $this->post('objId')
            ]
        ]);
        $and = "workFlow='已复核'";
        if ($mWhere) {
            $and .= " AND `jobId` IN ( SELECT `id` FROM `job` WHERE 1=1 $mWhere ) ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = $and.search(["like" => $like,"=" => $equal]);
        $page = $this->page(["table" => "staff", "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['stid']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'job':
                        $job = query('job', " id = '{$array['jobId']}' ");
                        $row[] = $job['name'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'].$button."<form name='listForm'>".$li."</form>".$page['button'].clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = "您还没有导出的权限";
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "stid in ('".implode("','", $checkedId)."') order by orderNo asc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $job = query('job', " id = '{$array['jobId']}' ");
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '职位'=>$job['name'],
                            '姓名'=>$array['name'],
                            '手机号'=>$array['tel'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text =str_replace(['{{staffName}}'],[$this->control['name']],L('person.table.staffExport'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('person.table.staffBook').'.xlsx');
            exit(0);
        }
        $locationUrl = root . 'control/adIndex.html?cla='.$this->get('cla').'&fun=home';
        header("Location:" . $locationUrl);
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'职位',
                    'aliasName'=>'职位',
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'手机号',
                    'aliasName'=>'手机号',
                ],
            ]
        };
    }
}
